package com.knowledge.graph.controller;

import com.knowledge.graph.exception.NonStaticResourceHttpRequestHandler;
import com.knowledge.graph.model.entity.Video;
import com.knowledge.graph.service.VideoService;
import com.knowledge.graph.model.vo.ResponseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

/**
 * @author jiwenlong
 * @version 1.0
 * @description: 处理有关视频对象的请求与响应
 * @date 2023/11/5 15:59
 */
@RestController
public class VideoController {

    @Autowired
    private VideoService videoService;

    @Autowired
    private NonStaticResourceHttpRequestHandler nonStaticResourceHttpRequestHandler;

    @PostMapping("/video")
    public ResponseVO<Integer> addVideo(@RequestPart("video") MultipartFile video, @RequestParam("courseID") Integer courseID,
                                        @RequestParam("nodeIDs") List<Integer> nodeIDs) {
        return videoService.addVideo(video, courseID, nodeIDs);
    }

    @GetMapping("/video")
    public ResponseVO getVideo(@RequestParam("courseID") Integer courseID) {
        return videoService.getVideo(courseID);
    }

    @GetMapping("/video/{id}")
    public void getVideoByID(@PathVariable("id") Integer videoID, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ResponseVO responseVO = videoService.getVideoByID(videoID);
        Video video = (Video) responseVO.getData();
        String videoAddress = video.getVideoAddress();
        Path path = new File(videoAddress).toPath();
        String contentType = Files.probeContentType(path);
        request.setAttribute("video", path);
        response.setContentType(contentType);
        nonStaticResourceHttpRequestHandler.handleRequest(request, response);
    }

    @PutMapping("/video")
    public ResponseVO updateVideo(@RequestParam("videoID") Integer videoID, @RequestParam("videoName") String videoName) {
        return videoService.update(videoID, videoName);
    }

    @DeleteMapping("/video")
    public ResponseVO deleteVideo(@RequestParam("videoID") Integer videoID) {
        return videoService.deleteVideo(videoID);
    }


}
